﻿using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Inlycat;
using Inlycat.Log;

namespace Inlycat
{

    namespace HotSwapping
    {
        public class FileUpdater : Singleton<FileUpdater>
        {
            public static string LocalConfigFilePath = "local_file_config.txt";
            private static string FileSaveDirectory = Application.persistentDataPath + "/";
            private static string Config_File_Path = Path.Combine(FileSaveDirectory, LocalConfigFilePath);

            private List<FileDownloader.FileInfo> UpdateInfos
            {
                get { return _fileDownloader.Files; }
                set { _fileDownloader.Files = value; }
            }
            private FileDownloader _fileDownloader;

            public bool IsCompleted { private set; get; }


            private FileUpdater()
            {
                _fileDownloader = new FileDownloader(true)
                {
                    LocalDirectory = FileSaveDirectory,

                };


                if (File.Exists(Config_File_Path))
                {
                    FileHelper.LoadFile(Config_File_Path, OnLoadConfigFile,
                        t =>
                        {
                            PLog.Log(t);
                        });
                }
            }

            private void OnLoadConfigFile(string content)
            {
                UpdateInfos = JsonConvert.DeserializeObject<List<FileDownloader.FileInfo>>(content);
            }

            private void OnSaveConfigFile(List<FileDownloader.FileInfo> fileinfos)
            {
                File.WriteAllText(Config_File_Path, JsonConvert.SerializeObject(fileinfos));
            }

            public void SetInfosAndUpdate(string url, Action onFinished)
            {
                CoroutineManager.Instance.DoAction(CoroutineRunner.WWWLoader(url, t =>
                {
                    PLog.Log(t.text);
                    UpdateInfos = JsonConvert.DeserializeObject<List<FileDownloader.FileInfo>>(t.text);
                    t.Dispose();

                    UpdateFiles();
                }));

                CoroutineManager.Instance.DoAction(WaiteForComplete(() =>
                {
                    onFinished();
                }));
            }

            IEnumerator WaiteForComplete(Action onComplete)
            {
                while (!IsCompleted)
                {
                    yield return null;
                }

                onComplete();
            }

            public void UpdateFiles()
            {
                if (UpdateInfos == null)
                {
                    return;
                }
                IsCompleted = false;
                // set callback and process etc.
                _fileDownloader.Completed += (sender, args) =>
                {// 全部下载成功的话，配置直接置空就行了 
                    OnSaveConfigFile(new List<FileDownloader.FileInfo>());
                    IsCompleted = true;
                };

                _fileDownloader.FileDownloadFailed += (sender, exception) =>
                {
                    OnSaveConfigFile(_fileDownloader.Files);
                };
                 
                _fileDownloader.ProgressChanged += (sender, args) =>
                {
                    PLog.Log(_fileDownloader.CurrentFile.Name.ToString());
                };

                _fileDownloader.Start();
                PLog.Log("Start");
            }


        }

    }

}